# @FileName  : bd.py
# @Time      : 2022/1/18 14:45
# @Author    : LuZhaoHui
# @Software  : PyCharm

import self as self
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

from hddata import Ui_MainWindow
from tool import *
import os, sys

ver = '1.22.6.30'


class hddataRun(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(hddataRun, self).__init__(parent)
        self.setupUi(self)
        self.config = hdConf('hd.ini')
        self.init()
        self.initUI()

    def init(self):
        if self.config.varConf['WindowMax'] > 0:
            self.showMaximized()
        self.setWindowTitle('%s-  [Ver %s]' % (self.config.varConf['Title'], ver))
        # 单位，类型
        setComboBoxHeight(self.comboBoxUnit, 16)
        setComboBoxHeight(self.comboBoxImgType, 16)
        self.unitPos = self.config.varConf['UnitPos']
        self.typePos = self.config.varConf['TypePos']
        if self.unitPos >= len(self.config.varUnitList):
            self.unitPos = -1
        if self.typePos >= len(self.config.varTypeList):
            self.typePos = -1

        # 配置路径，图片路径，备份路径
        self.confPath = self.config.varConf['ConfPath']
        self.imgPath = self.config.varConf['ImagePath']
        self.backupPath = self.config.varConf['BackupPath']

        # 文件列表选择
        self.scanThread = None
        self.procThread = None
        self.curFilePos = -1
        self.srcFileList = {}
        self.curFileList = []
        self.curProcDict = {}

    def initUI(self):
        # 单位
        self.comboBoxUnit.addItems(self.config.varUnitList)
        self.comboBoxUnit.setCurrentIndex(self.unitPos)
        self.comboBoxUnit.currentIndexChanged.connect(self.selectUnit)
        self.selectUnit(self.unitPos)
        # 类型
        self.comboBoxImgType.addItems(self.config.varTypeList)
        self.comboBoxImgType.setCurrentIndex(self.typePos)
        self.comboBoxImgType.currentIndexChanged.connect(self.selectType)
        self.selectType(self.typePos)

        # 扫描，处理
        self.pushButtonFileScan.clicked.connect(self.fileScan)
        self.pushButtonFileProc.clicked.connect(self.fileProc)
        # 配置路径，图片路径，备份路径
        self.lineEditConfPath.setText(self.confPath)
        self.pushButtonConfPath.clicked.connect(self.setConfPath)
        self.lineEditImgPath.setText(self.imgPath)
        self.pushButtonImgPath.clicked.connect(self.setImgPath)
        self.lineEditBackupPath.setText(self.backupPath)
        self.pushButtonBackupPath.clicked.connect(self.setBackupPath)
        # 选择文件
        a_group = QButtonGroup(self.centralwidget)
        a_group.addButton(self.radioButtonRotate0A)
        a_group.addButton(self.radioButtonRotate90A)
        a_group.addButton(self.radioButtonRotate180A)
        a_group.addButton(self.radioButtonRotate270A)
        b_group = QButtonGroup(self.centralwidget)
        b_group.addButton(self.radioButtonRotate90B)
        b_group.addButton(self.radioButtonRotate180B)
        b_group.addButton(self.radioButtonRotate270B)
        b_group.addButton(self.radioButtonRotate0B)
        # 文件处理配置
        self.radioButtonRotate0A.clicked.connect(self.procRadioRotate)
        self.radioButtonRotate90A.clicked.connect(self.procRadioRotate)
        self.radioButtonRotate180A.clicked.connect(self.procRadioRotate)
        self.radioButtonRotate270A.clicked.connect(self.procRadioRotate)
        self.radioButtonRotate90B.clicked.connect(self.procRadioRotate)
        self.radioButtonRotate180B.clicked.connect(self.procRadioRotate)
        self.radioButtonRotate270B.clicked.connect(self.procRadioRotate)
        self.radioButtonRotate0B.clicked.connect(self.procRadioRotate)
        self.checkBoxAtoB.clicked.connect(self.procCheckAtoB)
        self.checkBoxPixBtoA.clicked.connect(self.procCheckPixBtoA)
        # 文件列表
        # self.listWidgetCurFile.itemClicked.connect(self.selectCurFile)
        self.listWidgetCurFile.itemSelectionChanged.connect(self.selectCurFile)

    # 选择单位
    def selectUnit(self, index):
        self.unitName = ''
        if index < 0:
            return
        if self.unitPos != index:
            # self.config.writeConf('UnitPos', index)
            self.unitPos = index
        self.unitName = self.comboBoxUnit.currentText()
        if self.unitName not in self.srcFileList.keys():
            self.srcFileList[self.unitName] = []

    # 选择类型
    def selectType(self, index):
        self.typeName = ''
        if index < 0:
            return
        if self.typePos != index:
            # self.config.writeConf('TypePos', index)
            self.typePos = index
        if index > 0:
            self.typeName = self.comboBoxImgType.currentText()

    # 扫描
    def fileScan(self):
        self.keys = self.lineEditImgKeyword.text()
        self.isHave = self.checkBoxIsHave.isChecked()
        #
        self.listWidgetCurFile.clear()
        self.curFileList.clear()
        csvName = pathJoin(self.confPath, '%s.txt' % (self.unitName))
        self.scanThread = ScanSrcFileListThread(self.srcFileList[self.unitName], csvName)
        self.scanThread.update_item.connect(self.showSrcFileList)
        self.scanThread.start()

    def showSrcFileList(self, flist):
        if len(flist) == 1:
            self.lineEditFileInfo.setText(flist[0])
        elif len(flist) == 11:
            pname = '%s/%s' % (self.unitName, self.typeName)
            if pname != flist[3][:len(pname)]:
                return
            if len(self.keys) > 0:
                pname = os.path.basename(flist[3])
                if self.keys not in pname:
                    return
            self.curFileList.append(
                [flist[0], flist[3][len(self.unitName) + 1:], int(flist[6]), int(flist[6]), flist[9], '0000'])
            self.lineEditFileInfo.setText('%d-%s' % (flist[0], flist[3]))
            item = QListWidgetItem('%s   %s' % (flist[3][len(self.unitName) + 1:], '0000'))
            self.listWidgetCurFile.addItem(item)
        else:
            self.curProcDict = {}
            self.curFilePos = 0
            self.listWidgetCurFile.setCurrentRow(self.curFilePos)
            self.lineEditFileInfo.setText('%d' % (len(self.curFileList)))

    # 处理
    def fileProc(self):
        if len(self.curFileList) == 0:
            return
        self.procThread = ProcFileListThread(self.curProcDict)
        self.procThread.update_item.connect(self.showProcFileList)
        self.procThread.start()

    # 备份
    def procBackup(self, name):
        msg = '备份'
        sname = pathJoin(self.imgPath, '%s/%s' % (self.unitName, name))
        dname = pathJoin(self.backupPath, '%s/%s' % (self.unitName, name))
        copyFile(sname, dname)
        saveLog('%s %s->%s' % (msg, sname, dname), self.backupPath)

    # 旋转
    def procRotate(self, name, set):
        msg = '旋转' + str(ROTATE_TYPE[set])
        file = pathJoin(self.imgPath, '%s/%s' % (self.unitName, name))
        rotateImage(file, set)
        saveLog('%s %s' % (msg, file), self.backupPath)

    # 置换
    def procAB(self, name):
        msg = 'AB置换'
        nameA = pathJoin(self.imgPath, '%s/%s' % (self.unitName, name))
        nameTemp = nameA + '.temp'
        nameB = pathJoin(self.imgPath, '%s/%s' % (self.unitName, self.getNameAtoB(name)))
        os.rename(nameA, nameTemp)
        os.rename(nameB, nameA)
        os.rename(nameTemp, nameB)
        saveLog('%s %s->%s' % (msg, nameA, nameB), self.backupPath)

    # 像素BA
    def procPixBA(self, name):
        msg = '像素BtoA'
        nameA = pathJoin(self.imgPath, '%s/%s' % (self.unitName, name))
        nameB = pathJoin(self.imgPath, '%s/%s' % (self.unitName, self.getNameAtoB(name)))
        resizeImage(nameA,nameB)
        saveLog('%s %s->%s' % (msg, nameB, nameA), self.backupPath)

    def showProcFileList(self, flist):
        if len(flist) == 1:
            f = self.curFileList[flist[0]]
            self.lineEditFileInfo.setText('%d-%s-%s' % (f[0], f[1], f[5]))
            # nameA = pathJoin(self.imgPath, '%s/%s' % (self.unitName, flist[1]))
            # nameB = pathJoin(self.imgPath, '%s/%s' % (self.unitName, self.getNameAtoB(flist[1])))
            sets = list(f[5])
            if sets[0] != '0' or sets[1] != '0':
                self.procBackup(f[1])
            if sets[2] != '0' or sets[1] != '0':
                self.procBackup(self.getNameAtoB(f[1]))
            if sets[0] != '0':
                self.procRotate(f[1], sets[0])
            if sets[2] != '0':
                self.procRotate(self.getNameAtoB(f[1]), sets[2])
            if sets[1] == '1':
                self.procAB(f[1])
            if sets[3] == '1':
                self.procPixBA(f[1])
            # 刷新
            f[5] = '0000'
            self.curFilePos = flist[0]
            self.listFlush()
            self.flushProcState()

    # 配置路径
    def setConfPath(self):
        path = QFileDialog.getExistingDirectory(self, " 选择配置路径 ", self.confPath)
        if os.path.exists(path):
            if path != self.confPath:
                self.confPath = path
                self.config.writeConf('ConfPath', path)
                self.lineEditConfPath.setText(self.confPath)

    # 图片路径
    def setImgPath(self):
        path = QFileDialog.getExistingDirectory(self, " 选择图片路径 ", self.imgPath)
        if os.path.exists(path):
            if path != self.imgPath:
                self.imgPath = path
                self.config.writeConf('ImagePath', path)
                self.lineEditImgPath.setText(self.imgPath)

    # 备份路径
    def setBackupPath(self):
        path = QFileDialog.getExistingDirectory(self, " 选择备份路径 ", self.backupPath)
        if os.path.exists(path):
            if path != self.backupPath:
                self.backupPath = path
                self.config.writeConf('BackupPath', path)
                self.lineEditBackupPath.setText(self.backupPath)

    def getNameAtoB(self, name):
        ext = name[-5:]
        return name[:-5] + 'B' + ext[1:]

    # 选择旋转
    def procRadioRotate(self):
        if len(self.curFileList) == 0:
            return
        # radioButton = self.sender()
        # objName = radioButton.objectName()
        self.flushProcState()

    # AB置换
    def procCheckAtoB(self):
        if len(self.curFileList) == 0:
            return
        state = self.checkBoxAtoB.isChecked()
        print(state)
        self.flushProcState()

    # 像素B-A
    def procCheckPixBtoA(self):
        if len(self.curFileList) == 0:
            return
        state = self.checkBoxPixBtoA.isChecked()
        print(state)
        self.flushProcState()

    def setProcState(self, sets):
        for i, a in enumerate(sets):
            # print(i, a)
            if i == 1:
                self.checkBoxAtoB.setChecked(a == '1')
                continue
            if i == 3:
                self.checkBoxPixBtoA.setChecked(a == '1')
                continue
            if i == 0:
                # A
                if a == '0':
                    self.radioButtonRotate0A.setChecked(True)
                    self.radioButtonRotate90A.setChecked(False)
                    self.radioButtonRotate180A.setChecked(False)
                    self.radioButtonRotate270A.setChecked(False)
                elif a == '1':
                    self.radioButtonRotate0A.setChecked(False)
                    self.radioButtonRotate90A.setChecked(True)
                    self.radioButtonRotate180A.setChecked(False)
                    self.radioButtonRotate270A.setChecked(False)
                elif a == '2':
                    self.radioButtonRotate0A.setChecked(False)
                    self.radioButtonRotate90A.setChecked(False)
                    self.radioButtonRotate180A.setChecked(True)
                    self.radioButtonRotate270A.setChecked(False)
                elif a == '3':
                    self.radioButtonRotate0A.setChecked(False)
                    self.radioButtonRotate90A.setChecked(False)
                    self.radioButtonRotate180A.setChecked(False)
                    self.radioButtonRotate270A.setChecked(True)
            else:
                # B
                if a == '0':
                    self.radioButtonRotate0B.setChecked(True)
                    self.radioButtonRotate90B.setChecked(False)
                    self.radioButtonRotate180B.setChecked(False)
                    self.radioButtonRotate270B.setChecked(False)
                elif a == '1':
                    self.radioButtonRotate0B.setChecked(False)
                    self.radioButtonRotate90B.setChecked(True)
                    self.radioButtonRotate180B.setChecked(False)
                    self.radioButtonRotate270B.setChecked(False)
                elif a == '2':
                    self.radioButtonRotate0B.setChecked(False)
                    self.radioButtonRotate90B.setChecked(False)
                    self.radioButtonRotate180B.setChecked(True)
                    self.radioButtonRotate270B.setChecked(False)
                elif a == '3':
                    self.radioButtonRotate0B.setChecked(False)
                    self.radioButtonRotate90B.setChecked(False)
                    self.radioButtonRotate180B.setChecked(False)
                    self.radioButtonRotate270B.setChecked(True)

    def getProcState(self):
        sets = list('0000')
        sets[1] = '1' if self.checkBoxAtoB.isChecked() else '0'
        if self.radioButtonRotate90A.isChecked():
            sets[0] = '1'
        if self.radioButtonRotate180A.isChecked():
            sets[0] = '2'
        if self.radioButtonRotate270A.isChecked():
            sets[0] = '3'
        if self.radioButtonRotate90B.isChecked():
            sets[2] = '1'
        if self.radioButtonRotate180B.isChecked():
            sets[2] = '2'
        if self.radioButtonRotate270B.isChecked():
            sets[2] = '3'
        sets[3] = '1' if self.checkBoxPixBtoA.isChecked() else '0'
        return ''.join(sets)

    def flushProcState(self):
        item = self.listWidgetCurFile.item(self.curFilePos)
        flist = self.curFileList[self.curFilePos]
        sets = flist[5]
        flist[5] = self.getProcState()
        item.setText('%s   %s' % (flist[1], flist[5]))
        self.curProcDict[self.curFilePos] = flist[5]
        self.lineEditProcNums.setText('总数-%d' % (len(self.curProcDict)))
        # self.main.listWidgetAnalyseSrcFile.scrollToItem(item, QAbstractItemView.PositionAtBottom)

    # 选择文件
    def selectCurFile(self):
        try:
            index = self.listWidgetCurFile.selectedIndexes()[0].row()
        except Exception:
            return
        self.curFilePos = index
        # self.lineEditProcNums
        self.listFlush()

    def keyPressEvent(self, event):
        key = event.key()
        print("press: " + str(key))
        # if key == Qt.Key_Enter:
        # print("press: enter")
        # self.renameFiles()
        if key == Qt.Key_Up:
            self.listUp()
        elif key == Qt.Key_Down:
            self.listDown()
        elif key == Qt.Key_Q and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.radioButtonRotate90A.click()
        elif key == Qt.Key_W and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.radioButtonRotate180A.click()
        elif key == Qt.Key_E and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.radioButtonRotate270A.click()
        elif key == Qt.Key_A and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.radioButtonRotate90B.click()
        elif key == Qt.Key_S and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.radioButtonRotate180B.click()
        elif key == Qt.Key_D and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.radioButtonRotate270B.click()
        elif key == Qt.Key_Z and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.radioButtonRotate0A.click()
        elif key == Qt.Key_X and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.radioButtonRotate0B.click()
        elif key == Qt.Key_V and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.checkBoxAtoB.click()
        elif key == Qt.Key_C and QApplication.keyboardModifiers() == Qt.AltModifier:
            self.checkBoxPixBtoA.click()
        # elif key == Qt.Key_Left or key == Qt.Key_PageUp:
        #     self.listPageUp()
        # elif key == Qt.Key_Right or key == Qt.Key_PageDown:
        #     self.listPageDown()

    def getImgInfo(self, name, flist):
        img = getImgFile(name, False)
        return '%s 图片[pix:%dx%d dpi:%dx%d  %s] 内容%s' % (name, img[0], img[1], img[2], img[3], img[4], flist[4])

    def listFlush(self):
        self.listWidgetCurFile.setFocus()
        self.listWidgetCurFile.setCurrentRow(self.curFilePos)
        flist = self.curFileList[self.curFilePos]
        self.setProcState(list(flist[5]))
        # 显示图片A
        name = pathJoin(self.imgPath, '%s/%s' % (self.unitName, flist[1]))
        self.lineEditImgInfoA.setText(self.getImgInfo(name, flist))
        showLabelImage(self.scrollAreaA, self.labelCurImageA, name, True)
        # 显示图片B
        name = pathJoin(self.imgPath, '%s/%s' % (self.unitName, self.getNameAtoB(flist[1])))
        self.lineEditImgInfoB.setText(self.getImgInfo(name, flist))
        showLabelImage(self.scrollAreaB, self.labelCurImageB, name, True)

    def getIndex(self, c):
        if self.curFilePos < 0 or len(self.curFileList) == 0:
            return False
        #
        old = self.curFilePos
        index = self.curFilePos + c
        if c > 0:
            if index < len(self.curFileList):
                self.curFilePos = index
            else:
                self.curFilePos = len(self.curFileList) - 1
        else:
            if index >= 0:
                self.curFilePos = index
            else:
                self.curFilePos = 0
        return self.curFilePos != old

    def listUp(self):
        if self.getIndex(-1):
            self.listFlush()

    # def listPageUp(self):
    #     if self.getIndex(-10):
    #         self.listFlush()
    #
    def listDown(self):
        if self.getIndex(1):
            self.listFlush()
    #
    # def listPageDown(self):
    #     if self.getIndex(10):
    #         self.listFlush()
    #


if __name__ == '__main__':
    app = QApplication(sys.argv)

    main = hddataRun()
    main.show()

    sys.exit(app.exec_())
